package com.example.demo.util;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 多线程进行请求的工具类
 *
 * @author zyc
 */
public class MyManyThreadRequest {

    private ExecutorService threadPool = Executors.newCachedThreadPool();

    private CountDownLatch countDownLatch;
    /**
     * 总任务数
     */
    private int            taskNum;
    /**
     * 成功放入线程池的任务数
     */
    private AtomicInteger  successTaskNum = new AtomicInteger(0);

    public MyManyThreadRequest(RunTask task, int taskNum) {
        if (taskNum <= 0) {
            throw new RuntimeException("线程数必须大于0");
        }
        if (task == null) {
            throw new RuntimeException("任务不能为空");
        }
        this.taskNum = taskNum;
        countDownLatch = new CountDownLatch(taskNum);
        for (int i = 0; i < taskNum; i++) {
            threadPool.execute(() -> {
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                task.task();
                this.successTaskNum.incrementAndGet();
            });
            countDownLatch.countDown();
        }
    }

    public void shutdown() {
        threadPool.shutdown();
    }
    public int getSuccessTaskNum(){
        return this.successTaskNum.get();
    }

    @FunctionalInterface
    public interface RunTask {
        /**
         * 需要运行的方法
         */
        void task();
    }
}
